// pages/songDetail/songDetail.js
import request from "../../../utils/request";
import PubSub from "pubsub-js"
import moment, {duration} from "moment";
const appInstance = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPlay:false,
    song:{},//歌曲详情对象
    musicId:null,
    songIndex:null,
    currentTime:"00:00",
    durationTime:"00:00",
    duration:0,
    currentWidth:0,
    userId:null,
    starSrcRed:"/static/images/songbar/dianzan_red.png",
    starSrcGrey:"/static/images/songbar/dianzan_grey.png",
    starSrc:"/static/images/songbar/dianzan_grey.png",


    collectSrcRed:"/static/images/songbar/shoucang_red.png",
    collectSrcGrey:"/static/images/songbar/shoucang_grey.png",
    collectSrc:"/static/images/songbar/shoucang_grey.png",

    commentSrcGrey:"/static/images/songbar/pinglun_grey.png",
    commentSrc:"/static/images/songbar/pinglun_grey.png",
    startCount:0,
    commentCount:0,

    isDragging: false, // 是否正在拖动
    startX: 0, // 触摸开始X坐标
    currentX: 0, // 当前X坐标
    progressWidthRpx:450,
    ratio:1,
    sourceX:0,
    windowWidth:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  let musicId = options.musicId
    if(appInstance.globalData.isMusicPlay){
      if(appInstance.globalData.musicId === musicId){
        this.setData({
          isPlay:true
        })
      }else{
        this.setData({
          isPlay:false
        })
      }
    }
    const info = wx.getSystemInfoSync();
    this.setData({
      windowWidth:info.windowWidth,
    });
    this.geMusicInfo(musicId)
    this.setData({
      musicId
    })

    const query = wx.createSelectorQuery();
    query.select('.barControl').boundingClientRect(rect => {
      let temp = this.data.progressWidthRpx/rect.width
      this.setData({
          ratio:temp,
          sourceX:(this.data.windowWidth - rect.width)/2
      })
    }).exec()
    this.backgroundAudioManager = wx.getBackgroundAudioManager()
    this.handleMusicPlay()
    this.backgroundAudioManager.onPlay( ()=>{
      let dt = this.backgroundAudioManager.duration*1000
      this.setData({
        duration:dt,
      })
      appInstance.globalData.musicId = musicId
     this.changePlayState(true)
    })
    this.backgroundAudioManager.onPause( ()=>{
      this.changePlayState(false)
    })
    this.backgroundAudioManager.onStop( ()=>{
      this.changePlayState(false)
    })
  
    // 监听音乐实时进度
    this.backgroundAudioManager.onTimeUpdate(()=>{
      let durationTime = moment(this.data.duration).format("mm:ss")
        if (!this.data.isDragging){
            let currentTime = moment(this.backgroundAudioManager.currentTime * 1000).format("mm:ss")
            let currentWidth = (this.backgroundAudioManager.currentTime/this.backgroundAudioManager.duration) * 450
            this.setData({
                durationTime,
                currentTime,
                currentWidth
            })
        }
    })
    // 监听音乐播放自然结束
    this.backgroundAudioManager.onEnded(() => {
      // 切换到下一首自动播放
      PubSub.publish('switchType', "next")
      this.setData({
        currentWidth: 0,
        currentTime:"00:00"
      })
    })
    let userInfo = wx.getStorageSync("userInfo")
    this.setData({
      userId:JSON.parse(userInfo).id
    })

    request("/song/isInLikedCollect",{userId:this.data.userId, songId: this.data.musicId}, 'POST').then((resp)=>{
      this.setData({
        starSrc:resp.data.isLiked ? this.data.starSrcRed : this.data.starSrcGrey,
        collectSrc:resp.data.isCollect ? this.data.collectSrcRed : this.data.collectSrcGrey,
        commentCount:resp.data.commentCount?resp.data.commentCount:0,
        startCount:resp.data.startCount?resp.data.startCount:0
      })

    })
  },

  changePlayState(isPlay){
    this.setData({
      isPlay
    })
    appInstance.globalData.isMusicPlay = isPlay
  },

  async geMusicInfo(musicId){

    let songData = await request("/song/detail",{ids: musicId})

    let durationTime = moment(this.data.duration).format("mm:ss")

    this.setData({
      song: songData.songs[0],
      durationTime:durationTime
    })
    wx.setNavigationBarTitle({title:this.data.song.name})
  },
  handleMusicPlay(){
    let isPlay = !this.data.isPlay
    this.setData({
      isPlay
    })
    this.musicControl(isPlay, this.data.musicId, this.data.musicLink)
  },

  async musicControl(isPlay, musicId, musicLink){
    if(isPlay){
      if(!musicLink){
        // 播放
        let songData = await request("/song/url",{id: musicId})
        musicLink = songData.data[0].url
        this.setData({
          musicLink
        })
      }

      this.backgroundAudioManager.src = musicLink
      this.backgroundAudioManager.title = this.data.song.name
    }else{
      // 暂停
      this.backgroundAudioManager.pause()
    }
    },
  handleSwitch(event){

    PubSub.subscribe("musicId",  (msg, musicId) => {
      this.geMusicInfo(musicId)
      this.musicControl("true", musicId)
      // 取消订阅
      PubSub.unsubscribe("musicId")
    })
    this.backgroundAudioManager.stop()
    let type = event.currentTarget.dataset.type

    PubSub.publish('switchType', type)
  },
  clickStar(){
   if(this.data.starSrc==this.data.starSrcGrey){// 灰色变红色

     request("/song/addLiked",{userId:this.data.userId, songId: this.data.musicId}, 'POST').then((data)=>{
       this.setData({
         starSrc:this.data.starSrcRed,
         startCount:this.data.startCount+1
       })
     },(error)=>{

     })

   }else{// 红色变灰色
     request("/song/removeLiked",{userId:this.data.userId, songId: this.data.musicId}, 'POST').then((data)=>{
       this.setData({
         starSrc:this.data.starSrcGrey,
         startCount:this.data.startCount-1
       })
     },(error)=>{

     })
   }
  },
  clickCollect(){
   if(this.data.collectSrc==this.data.collectSrcGrey){// 灰色变红色

     request("/song/addCollect",{userId:this.data.userId, songId: this.data.musicId}, 'POST').then((data)=>{
       this.setData({
         collectSrc:this.data.collectSrcRed,
       })
     },(error)=>{

     })
   }else{// 红色变灰色
     request("/song/removeCollect",{userId:this.data.userId, songId: this.data.musicId}, 'POST').then((data)=>{
       this.setData({
         collectSrc:this.data.collectSrcGrey,
       })
     },(error)=>{

     })
   }
  },
  clickComment(){
    wx.navigateTo({
      url:"/songPackage/pages/songComment/songComment?musicId=" + this.data.musicId+"&userId=" + this.data.userId
    })
  },

    // 开始触摸滑块
    onThumbTouchStart(e) {

        this.setData({
            isDragging: true,
            startX: e.touches[0].clientX,
        });
    },

    // 拖动滑块
    onThumbTouchMove(e) {
        if (!this.data.isDragging) return;
        const clientX = e.touches[0].clientX
        let temp =  (clientX - this.data.sourceX)*this.data.ratio
        if(temp<0){
            temp = 0
        }else if(temp>450){
            temp = 450
        }
        this.setData({
             currentWidth: temp,
        });
    },

    // 结束触摸滑块
    onThumbTouchEnd() {

        this.setData({
            isDragging: false,
        });
       let persent =  (this.data.currentWidth/450)
        this.backgroundAudioManager.seek((this.data.duration/1000)*persent)
    },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let newNum = wx.getStorageSync("myContentNum")
    this.setData({
      commentCount:this.data.commentCount+newNum
    })
    wx.setStorageSync("myContentNum",0)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})